import store from '@/store'

// 查找条文脚注对应位置的前一个元素，方便插入
export function getPrevElementInFooter(footer, number) {
  return footer.querySelector(`p.item-footnote[data-number="${number-1}"]`) || footer.firstChild
}

// 刷新条文脚注的编号
export const refreshItemFootnoteNumbers = (editor) => {
  const doc = editor.getDoc()
  const pages = doc.querySelectorAll('.page-sheet')
  let number = 0
  const languageType = store.getters.languageType
  pages.forEach(page => {
    // 刷新正文中标记的编号
    const tags = page.querySelectorAll('span.item_footnote')
    const pageFoot = page.querySelector('.page_footnote')
    if (!pageFoot) return
    pageFoot.querySelectorAll('p.item_footnote')?.forEach?.(e => e.remove())
    let htmlZh = '', htmlEn = ''
    tags.forEach(tag => {
      editor.dom.setAttrib(tag, 'data-number', ++number)
      editor.dom.setHTML(tag, `${number})`)
      // 刷新页脚的条文脚注内容
      htmlZh += `
        <p data-referred-id="${tag.dataset.id}"
          data-number="${number}"
          data-type="footnote"
          contenteditable="false"
          class="item_footnote in-footer zh"
          data-lang="zh"
        >${tag.dataset.contentZh}</p>
      `
      if (languageType === 'both') {
        htmlEn += `
          <p data-referred-id="${tag.dataset.id}"
            data-number="${number}"
            data-type="footnote"
            contenteditable="false"
            class="item_footnote in-footer en"
            data-lang="en"
          >${tag.dataset.contentEn}</p>
        `
      }
    })
    const _h = htmlZh + htmlEn
    pageFoot.innerHTML += _h
    pageFoot.style.display = _h.length > 0 ? 'block' : 'none'
  })
}